package com.qqtech.qquan.homemaking.controller;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Calendar;

import javax.annotation.Resource;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.qqtech.core.common.annotation.VisitAnnt;
import com.qqtech.core.common.enums.RespEnum;
import com.qqtech.core.common.exception.OrderException;
import com.qqtech.core.common.util.StringUtil;
import com.qqtech.core.common.util.TimeUtil;
import com.qqtech.core.frame.model.PageKit;
import com.qqtech.core.frame.model.PageOrder;
import com.qqtech.core.frame.model.Result;
import com.qqtech.core.frame.service.BaseService;
import com.qqtech.qquan.homemaking.enums.HomemakingBaseConst;
import com.qqtech.qquan.homemaking.model.HomemakingBase;
import com.qqtech.qquan.homemaking.model.HomemakingBaseVo;
import com.qqtech.qquan.homemaking.model.HomemakingOrder;
import com.qqtech.qquan.homemaking.model.HomemakingOrderItemVo;
import com.qqtech.qquan.homemaking.model.HomemakingOrderQuery;
import com.qqtech.qquan.homemaking.model.HomemakingOrderVo;
import com.qqtech.qquan.homemaking.model.HomemakingTimeVo;
import com.qqtech.qquan.homemaking.service.HomemakingBaseService;
import com.qqtech.qquan.homemaking.service.HomemakingOrderService;
import com.qqtech.qquan.homemaking.service.HomemakingTimeService;
import com.qqtech.qquan.user.model.UserLoginVo;
import com.qqtech.web.context.BaseWebController;

@Controller
@RequestMapping(value = "/homemaking/order")
public class HomemakingOrderController extends
		BaseWebController<HomemakingOrder, HomemakingOrderQuery> {
	@Resource
	private HomemakingOrderService homemakingOrderService;

	@Resource
	private HomemakingTimeService homemakingTimeService;

	@Resource
	private HomemakingBaseService homemakingBaseService;

	@Override
	protected BaseService<HomemakingOrder> getBaseService() {
		return homemakingOrderService;
	}

	@VisitAnnt(type = RespEnum.LOGIN)
	@RequestMapping(value = "/add")
	@ResponseBody
	public Result add(@RequestBody HomemakingOrderVo homemakingOrderVo) throws OrderException {
		UserLoginVo userLoginVo = super.getLoginUser();
		Integer userId = userLoginVo.getId();
		Result result = new Result();
		if (homemakingOrderVo == null
				|| homemakingOrderVo.getHomemakingOrderItemVos() == null) {
			result.addErr("参数不能为空");
		} else {
			if (homemakingOrderVo.getBaseId() == null) {
				result.addErr("请选择服务人员");
			}
			if (homemakingOrderVo.getAddressId() == null) {
				result.addErr("地址不能为空");
			}
			if (StringUtil.isBlank(homemakingOrderVo.getServiceDateStr())
					|| StringUtil.isBlank(homemakingOrderVo.getServiceHourStr())) {
				result.addErr("服务时间不能为空");
			} else {
				Calendar calendar = Calendar.getInstance();
				String year = String.valueOf(calendar.get(Calendar.YEAR));
				if (!homemakingOrderVo.getServiceHourStr().equals("马上预定")) {
					Timestamp tempAt = TimeUtil.getTimeByFormat(homemakingOrderVo.getServiceDateStr() + " "
							+ homemakingOrderVo.getServiceHourStr() + ":00",
							TimeUtil.DATE_TIME_FORMAT);
					if (tempAt.before(TimeUtil.now())) {
						result.addErr("该时间已无效");
					}
				}
				if (homemakingOrderVo.getBaseId() != null) {
					boolean checkTime = homemakingTimeService.checkHomemakingTime(
							homemakingOrderVo.getBaseId(),
							homemakingOrderVo.getServiceDateStr(),
							homemakingOrderVo.getServiceHourStr().split(":")[0]+ ":00");
					if (checkTime) {
						result.addErr("该时间已经被预约");
					}
				}
			}

			int t = 0;
			for (HomemakingOrderItemVo item : homemakingOrderVo
					.getHomemakingOrderItemVos()) {
				if (item.getCount() == null || item.getCount() == 0) {
					item.setCount(0);
					t++;
				}
			}
			if (t == homemakingOrderVo.getHomemakingOrderItemVos().size()) {
				result.addErr("请选择一项服务");
			} else {
				for (HomemakingOrderItemVo item : homemakingOrderVo
						.getHomemakingOrderItemVos()) {
					if (item.getCount().intValue() < 0) {
						result.addErr("数量不能是负数");
						break;
					}
				}
			}
		}
		if (result.checkForm()) {
			Calendar calendar = Calendar.getInstance();
			String year = String.valueOf(calendar.get(Calendar.YEAR));
			homemakingOrderVo.setHomemakingTimeVos(new ArrayList<HomemakingTimeVo>());
			HomemakingBase homemakingBase = homemakingBaseService
					.getById(homemakingOrderVo.getBaseId());
			//日常保洁有选择时间段的，比如8点开始，需要2小时，就是8点，9点
			//7点30分的 按7点来查询
			if (homemakingBase.getTypeId().intValue() == HomemakingBaseConst.RI_CHANG_BAO_JIE_ID) {
				int hours = homemakingOrderVo.getHomemakingOrderItemVos().get(0).getCount();
				for (int i = 0; i < hours; i++) {
					int hour = Integer.valueOf(homemakingOrderVo.getServiceHourStr().split(":")[0]) + i;
					HomemakingTimeVo homemakingTimeVoTemp = new HomemakingTimeVo();
					homemakingTimeVoTemp.setServiceDateStr(homemakingOrderVo.getServiceDateStr());
					homemakingTimeVoTemp.setServiceHourStr(hour + ":00");
					homemakingOrderVo.getHomemakingTimeVos().add(homemakingTimeVoTemp);
				}
			} else {
				HomemakingTimeVo homemakingTimeVoTemp = new HomemakingTimeVo();
				homemakingTimeVoTemp.setServiceDateStr(homemakingOrderVo.getServiceDateStr());
				homemakingTimeVoTemp.setServiceHourStr(homemakingOrderVo.getServiceHourStr());
				homemakingOrderVo.getHomemakingTimeVos().add(homemakingTimeVoTemp);
			}
			homemakingOrderVo.setServiceDateStr(homemakingOrderVo.getServiceDateStr());
			homemakingOrderVo.setBuyerId(userId);
			if (homemakingOrderVo.getServiceHourStr().equals("马上预定")) {
				homemakingOrderVo.setServiceAt(TimeUtil.now());
			} else {
				Timestamp serviceAt = TimeUtil.getTimeByFormat(homemakingOrderVo.getServiceDateStr() + " "
						+ homemakingOrderVo.getServiceHourStr() + ":00",
						TimeUtil.DATE_TIME_FORMAT);
				homemakingOrderVo.setServiceAt(serviceAt);
			}
			result = homemakingOrderService.handleSaveOrder(homemakingOrderVo);
		}
		return result;
	}

	/**
	 * 向我预约的
	 * 
	 * @param homemakingOrderQuery
	 * @return
	 */
	@VisitAnnt(type = RespEnum.LOGIN)
	@RequestMapping(value = "/myPage")
	@ResponseBody
	public Result myPage(@RequestBody HomemakingOrderQuery homemakingOrderQuery) {
		Result result = new Result();
		if (homemakingOrderQuery == null
				|| homemakingOrderQuery.getBaseId() == null) {
			result.addErr("参数不能为空");
		} else {
			HomemakingBase homemakingBase = homemakingBaseService
					.getById(homemakingOrderQuery.getBaseId());
			if (homemakingBase == null) {
				result.addErr("数据不对");
			} else if (homemakingBase.getCreatorId().intValue() != super
					.getUserId()) {
				result.addErr("没有权限");
			}
		}
		if (result.checkForm()) {
			Pageable pageKit = new PageKit(homemakingOrderQuery.getPage(),
					new PageOrder(Direction.ASC, "base.`status`"),new PageOrder(Direction.DESC, "o.`payStatus`"),new PageOrder(Direction.ASC, "serviceAt"));
			Page<HomemakingOrderVo> page = homemakingOrderService
					.queryPageListBySeller(homemakingOrderQuery, pageKit);
			result.put("page", page);
		}
		return result;
	}
	
	/**
	 * 设置完成服务 等于卖家发货
	 * @param homemakingOrderVo
	 * @return
	 */
	@VisitAnnt(type = RespEnum.LOGIN)
	@RequestMapping(value = "/completeService")
	@ResponseBody
	public Result completeService(@RequestBody HomemakingOrderVo homemakingOrderVo) throws OrderException {
		Result result = new Result();
		UserLoginVo userLoginVo = super.getLoginUser();
		Integer userId = userLoginVo.getId();
		HomemakingOrderVo orderTemp = null;
		if (homemakingOrderVo.getId() != null) {
			orderTemp = homemakingOrderService.getById(homemakingOrderVo.getId());
		} else if (homemakingOrderVo.getOrderNo() != null) {
			orderTemp = homemakingOrderService.getByOrderNo(homemakingOrderVo.getOrderNo());
		}
		if (orderTemp == null) {
			result.addErr("系统繁忙，请联系管理员");
		} else {
			HomemakingBaseVo temp = homemakingBaseService
					.getById(orderTemp.getBaseId());
			if (temp.getCreatorId().intValue() != userId) {
				result.addErr("没有权限修改");
			}
		}
		if (result.checkForm()) {
			result = homemakingOrderService.handleCompleteService(orderTemp.getOrderNo());
		}
		return result;
	}
}
